package hu.ikti.oamadmin.beans.bundle;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import hu.ikti.oamadmin.beans.BaseBean;
import hu.ikti.oamadmin.types.entities.Bundle;
import hu.ikti.oamadmin.types.entities.Repository;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;

@Name("bundleListBean")
@Scope(ScopeType.SESSION)
public class BundleListBean extends BaseBean implements Serializable {

	private static final long serialVersionUID = 1L;

	@In(required = false, value = "selectedRepository")
	@Out(required = false, value = "selectedRepository")
	private Repository repository;

	@In(required = false)
	@Out(required = false)
	private List<Bundle> bundleList;

	@In(required = false)
	@Out(required = false)
	private Bundle bundle;

	@Factory(value = "bundleList")
	public void getBundleList() {
		if (repository == null) {
			bundleList = null;
		} else {
			List<?> results = entityManager
					.createQuery(
							"select bundle from Bundle bundle "
									+ "left outer join bundle.bundleData as bundleData "
									+ "left outer join bundleData.repository as repository "
									+ "where bundle.bundleData.deleted = false "
									+ "and repository = :repo "
									+ "and bundle.service = null "
									+ "and bundle.serviceProfile = null "
									+ "and bundle.gateway = null "
									+ "order by bundle.bundleData.symbolicName")
					.setParameter("repo", repository).getResultList();
			if (results != null) {
				bundleList = new ArrayList<Bundle>();
				for (Object object : results) {
					bundleList.add((Bundle) object);
				}
			}
		}
	}

	@Begin(join = true)
	public String bundleDetails() {
		bundle = (Bundle) entityManager
				.createQuery(
						"select bundle from Bundle bundle "
								+ "left outer join bundle.resources "
								+ "left outer join bundle.bundleData as bundleData "
								+ "left outer join bundleData.capabilities "
								+ "left outer join bundleData.requirements "
								+ "where bundleData.id = :id")
				.setParameter("id", bundle.getId()).getSingleResult();
		return "details";
	}

	@End
	public String back() {
		return "back";
	}

}
